<template>
  <div>
    <div class="select-with-search  !w-240px">
      <el-select
        v-model="selectedValue"
        filterable
        remote
        reserve-keyword
        placeholder="请输入产品编码/名称/规格"
        :remote-method="remoteMethod"
        :loading="loading"
        @change="handleSelectChange"
        @blur="handleBlur"
      >
        <!-- 自定义选中后的显示: 名称 + 条码 + 规格 -->
        <template #label>
          <span v-if="selectedProductDisplay" style="font-size: 12px">
            <span style="font-weight: bold">{{ selectedProductDisplay.name }}</span>
            <span style="color: gray; margin-left: 6px">
              {{ "(" + selectedProductDisplay.barCode + ")" }}
            </span>
            <span v-if="selectedProductDisplay.standard" style="color: #409eff; margin-left: 6px">
              {{ "[" + selectedProductDisplay.standard + "]" }}
            </span>
          </span>
        </template>
        <el-option
          v-for="item in options"
          :key="item.barCode"
          :label="item.name"
          :value="item.id"
        >
          <span style="font-weight: bold; font-size: 12px">{{ item.name }}</span>
          <span
            style="color: #8492a6; font-size: 11px; margin-left: 6px">{{ "(" + item.barCode + ")" }}</span>
          <span v-if="item.standard" style="color: #409eff; font-size: 11px; margin-left: 6px">{{
              "[" + item.standard + "]"
            }}</span>
        </el-option>
      </el-select>
      <el-button
        class="search-button"
        :icon="Search"
        @mousedown="handleSearchButtonMouseDown"
        @click="openSearchDialog"
      />
    </div>

    <!-- 商品搜索模态框 -->
    <el-dialog
      v-model="dialogVisible"
      title="选择商品"
      width="80%"
      :close-on-click-modal="false"
      draggable
      append-to-body
    >
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入名称"
            clearable
            class="!w-240px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="规格型号">
          <el-input
            v-model="searchForm.standard"
            placeholder="请输入规格"
            clearable
            class="!w-240px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="商品编码">
          <el-input
            v-model="searchForm.barCode"
            placeholder="商品编码"
            clearable
            class="!w-240px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" class="mr-5px">查询</el-button>
          <el-button @click="handleReset" class="mr-5px">重置</el-button>
          <el-button @click="handleConfirmSelect" type="success" class="mr-5px">确定</el-button>
        </el-form-item>
      </el-form>
      <el-alert
        type="info"
        :closable="false"
        show-icon
        title="提示：双击表格行可快速选择商品"
        style="margin-top: 10px"
      />

      <el-table
        :data="tableData"
        v-loading="tableLoading"
        stripe
        highlight-current-row
        @row-dblclick="handleRowDoubleClick"
        @current-change="handleCurrentChange"
        style="margin-top: 10px"
        max-height="500"
      >
        <el-table-column label="选择" width="60" align="center">
          <template #default="{ row }">
            <el-radio
              :model-value="currentRow?.id"
              :value="row.id"
              @change="handleCurrentChange(row)"
            >
              {{ '' }}
            </el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称" min-width="200" show-overflow-tooltip/>
        <el-table-column prop="barCode" label="商品编码" min-width="200"/>
        <el-table-column prop="standard" label="规格" width="120"/>
        <el-table-column prop="categoryName" label="分类" width="100"/>
        <el-table-column prop="property" label="产品属性" width="100"/>
        <el-table-column prop="unitName" label="单位" width="80"/>
        <!--        <el-table-column prop="weight" label="重量(kg)" width="100" align="right" />-->
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip/>
      </el-table>

      <el-pagination
        v-model:current-page="pagination.pageNo"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleQuery"
        @current-change="handleQuery"
        style="margin-top: 20px; justify-content: flex-end"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import {ProductApi} from '@/api/erp/product/product';
import {Search} from '@element-plus/icons-vue';
import {useProductStore} from '@/store/modules/erp/product';

const message = useMessage() // 消息弹窗


const productStore = useProductStore();

const props = defineProps({
  modelValue: {
    type: String, // 与父组件 formData.barCode 类型一致（通常是字符串）
    default: '' // 默认值为空
  }
});

// 3. 定义向父组件触发的事件（v-model 必须触发 update:modelValue）
const emit = defineEmits(['update:modelValue', 'select', 'change', 'blur']);

// 4. 响应式数据 - 原有的 select 组件
const options = ref([]);
const selectedValue = ref(props.modelValue); // 初始值同步父组件的 modelValue
const loading = ref(false);
const isClickingSearchButton = ref(false); // 标记是否正在点击搜索按钮

// 计算当前选中商品的完整信息,用于自定义显示（从 store 中获取）
const selectedProductDisplay = computed(() => {
  if (!selectedValue.value) return null;
  // 从 store 中获取产品信息
  return productStore.productMap.get(selectedValue.value) ||
    options.value.find(item => item.id === selectedValue.value);
});

// 新增：模态框相关数据
const dialogVisible = ref(false);
const tableData = ref([]);
const tableLoading = ref(false);
const currentRow = ref(null); // 当前选中的行
const searchForm = ref({
  searchValue: '',
  standard: '',
  color: ''
});
const pagination = ref({
  pageNo: 1,
  pageSize: 10,
  total: 0
});

// 5. 监听父组件 modelValue 变化：若父组件主动修改 formData.barCode，子组件同步更新
watch(
  () => props.modelValue,
  async (newVal) => {
    selectedValue.value = newVal;
    // 如果有值,从 store 中加载产品信息
    if (newVal) {
      await productStore.getProductById(newVal);
    }
  },
  {immediate: true}
);

// 根据产品ID加载产品详情(用于回显) - 已改用 store 统一管理
const loadProductById = async (productId) => {
  if (!productId) return;
  loading.value = true;
  try {
    const product = await productStore.getProductById(productId);
    if (product) {
      // 添加到 options 用于下拉选项显示
      const exists = options.value.some(item => item.id === product.id);
      if (!exists) {
        options.value.push(product);
      }
    }
  } catch (error) {
    console.error('加载产品详情失败:', error);
  } finally {
    loading.value = false;
  }
};

// 6. 远程搜索方法：优先从 store 缓存中搜索
const remoteMethod = async (query) => {
  if (!query.trim()) {
    options.value = [];
    selectedValue.value = '';
    emit('update:modelValue', ''); // 通知父组件清空值
    return;
  }

  loading.value = true;
  try {
    // 优先从 store 缓存中搜索
    const cachedResults = productStore.searchProducts(query);
    debugger
    if (cachedResults.length > 0) {
      options.value = cachedResults;
    } else {
      // 缓存中没有结果,调用远程搜索接口
      const products = await ProductApi.getProductRemoteSearch({searchValue: query});
      options.value = products;
      // 将搜索结果更新到 store
      products.forEach(product => {
        productStore.updateProduct(product);
      });
    }
  } catch (error) {
    message.error('搜索出错，请稍后重试');
    options.value = [];
  } finally {
    loading.value = false;
  }
};

// 7. 选中变化：触发 v-model 事件 + 传递完整商品数据（可选）
const handleSelectChange = () => {
  // （1）触发 update:modelValue：将选中的 barCode 传给父组件，更新 formData.barCode
  emit('update:modelValue', selectedValue.value);

  // （2）（可选）触发 select 事件：向父组件传递完整商品数据（如需要 id、name 等）
  const selectedProduct = options.value.find(
    item => item.id === selectedValue.value
  );
  if (selectedProduct) {
    emit('select', selectedProduct);
  } else {
    emit('select', null);
  }

  // （3）触发 change 事件，确保 el-form 能够清除验证错误
  emit('change', selectedValue.value);
};

// 8. 失焦事件：触发 blur 让表单验证生效（但点击搜索按钮时不触发）
const handleBlur = () => {
  // 如果是点击搜索按钮导致的失焦，不触发 blur 验证
  if (isClickingSearchButton.value) {
    return;
  }
  emit('blur');
};

// ========== 新增：模态框相关方法 ==========

// 搜索按钮鼠标按下事件（在 blur 之前触发）
const handleSearchButtonMouseDown = () => {
  // mousedown 会在 blur 之前触发，所以在这里设置标志
  isClickingSearchButton.value = true;
  // 延迟重置标志（等待 blur 事件处理完成）
  setTimeout(() => {
    isClickingSearchButton.value = false;
  }, 200);
};

// 打开搜索模态框
const openSearchDialog = () => {
  dialogVisible.value = true;
  // 重置搜索条件
  searchForm.value = {
    searchValue: '',
    standard: '',
    color: ''
  };
  pagination.value.pageNo = 1;
  // 加载初始数据
  handleQuery();
};

// 执行搜索
const handleQuery = async () => {
  tableLoading.value = true;
  try {
    const params = {
      pageNo: pagination.value.pageNo,
      pageSize: pagination.value.pageSize,
      ...searchForm.value
    };
    const response = await ProductApi.getProductPage(params);
    tableData.value = response.list || [];
    pagination.value.total = response.total || 0;
  } catch (error) {
    message.error('查询商品失败');
    tableData.value = [];
  } finally {
    tableLoading.value = false;
  }
};

// 重置搜索条件
const handleReset = () => {
  searchForm.value = {
    searchValue: '',
    standard: '',
    color: ''
  };
  pagination.value.pageNo = 1;
  handleQuery();
};

// 表格行双击选择
const handleRowDoubleClick = (row) => {
  selectProduct(row);
};

// 表格单选当前行变化
const handleCurrentChange = (row) => {
  currentRow.value = row;
};

// 确定按钮选择
const handleConfirmSelect = () => {
  if (!currentRow.value) {
    message.warning('请先选择一个商品');
    return;
  }
  selectProduct(currentRow.value);
};

// 选择商品的通用方法
const selectProduct = (product) => {
  // 1. 存入 store
  productStore.updateProduct(product);

  // 2. 将商品添加到 options 数组(如果不存在)
  const exists = options.value.some(item => item.id === product.id);
  if (!exists) {
    options.value.push(product);
  }

  // 3. 设置选中值
  selectedValue.value = product.id;

  // 4. 触发父组件更新
  emit('update:modelValue', product.id);
  emit('select', product);
  emit('change', product.id);
  emit('blur');

  // 5. 关闭弹窗并提示
  dialogVisible.value = false;
  message.success(`已选择商品: ${product.name}`);
};
</script>

<style scoped>
/* 选择框与搜索按钮容器 */
.select-with-search {
  display: flex;
  align-items: center;
  width: 100%;
}

/* el-select 占据剩余空间 */
:deep(.el-select) {
  flex: 1;
  width: 100%;
}

/* 移除 el-select 右侧圆角,使其与按钮紧密连接 */
:deep(.el-select .el-input__wrapper) {
  border-top-right-radius: 0 !important;
  border-bottom-right-radius: 0 !important;
}

/* 搜索按钮样式 */
.search-button {
  margin-left: -1px; /* 避免双重边框 */
  border-top-left-radius: 0; /* 移除左侧圆角 */
  border-bottom-left-radius: 0; /* 移除左侧圆角 */
  background-color: #ffffff; /* 白色背景 */
  border-color: var(--el-input-border-color, #dcdfe6); /* 与输入框相同边框色 */
  color: #606266; /* 图标颜色 */
  height: 32px; /* 与 el-select 相同高度 */
  padding: 0 12px; /* 调整内边距 */
}

/* 搜索按钮悬停效果 */
.search-button:hover {
  background-color: #f5f7fa;
  border-color: var(--el-input-hover-border-color, #c0c4cc);
  color: var(--el-color-primary, #409eff);
}

/* 搜索按钮激活效果 */
.search-button:active {
  background-color: #e6e8eb;
}

/* 确保按钮与输入框对齐 */
.search-button:focus {
  outline: none;
}

:deep(.el-option) {
  line-height: 32px !important;
  padding: 4px 16px !important;
}
</style>
